﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CashFlow.Web.MyActionResult
{
    public class MyJsonResult : JsonResult
    {
        public MyJsonResult(object data)
            : this(data, JsonRequestBehavior.AllowGet)
        {

        }

        public MyJsonResult(object data, JsonRequestBehavior jsonRequestBehavior)
        {
            this.Data = data;
            this.JsonRequestBehavior = jsonRequestBehavior;
            this.Settings = new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                DateFormatString = "yyyy-MM-dd HH:mm:ss",
                ContractResolver = new NullToEmptyStringResolver()
            };
        }

        /// <summary>
        /// JSON序列化设置对象
        /// </summary>
        public JsonSerializerSettings Settings { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            //判断当前请求是否为GET且判断是否允许GET获取JSON，不允许就报错
            if ("GET".Equals(context.HttpContext.Request.HttpMethod, StringComparison.OrdinalIgnoreCase) &&
                this.JsonRequestBehavior == JsonRequestBehavior.DenyGet)
                throw new Exception("不允许GET请求返回JSON数据！");

            //判断是否改变响应数据编码
            if (this.ContentEncoding != null)
                context.HttpContext.Response.ContentEncoding = this.ContentEncoding;
            //如果当前需要序列化的数据为NULL就直接返回
            if (this.Data == null)
                return;
            //设置响应数据内容格式为 json
            context.HttpContext.Response.ContentType =
                string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
            //向响应流写入序列化的数据
            JsonSerializer.Create(Settings).Serialize(context.HttpContext.Response.Output, this.Data);
        }
    }
}